﻿using AllInOne.Classes;
using AllInOne.Entity;
using AllInOne.HID;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AllInOne
{
    /// <summary>
    /// StartWindow.xaml 的交互逻辑
    /// </summary>
    public partial class Manual_MainWindow : Window
    {
        QueryT_RegisterInfoVM vm = new QueryT_RegisterInfoVM() { BeginTime = DateTimeHelper.FirstDay(), EndTime = DateTimeHelper.EndDay() };

        public Manual_MainWindow()
        {
            InitializeComponent();
            DataContext = vm;
            //初始化读卡器
            InitMingHuaIC();
            //Thread t = new Thread(MainLogicThread) { IsBackground = true };
            //t.Start();

            //初始化查询条件
            InitCondition();
            //初始化制卡类型条件
            InitCardType();
        }

        #region 主要逻辑线程
        private string RfidPlate = null;
        private volatile bool IsRun = true;
        private DateTime lastDateTime = DateTime.Now;
        public void MainLogicThread()
        {
            while (IsRun)
            {
                initMingHuaIC.StartRead();
                VoiceHelper.Speak("请刷卡");
                Thread.Sleep(500);
                if (string.IsNullOrEmpty(Inrfid))
                {
                    Thread.Sleep(100);
                    continue;
                }
                Thread.Sleep(10);
            }
        }

        #endregion

        private string Inrfid;
        private MingHuaICReader initMingHuaIC;

        private bool _icReaderState;
        public bool IcReaderState
        {
            get => _icReaderState;
            set
            {
                if (value == _icReaderState) return;
                _icReaderState = value;
                var state = _icReaderState ? "1" : "0";
                //Messenger.Default.Send($"{(int) ToCenterKeyEnum.读卡器} {state}");
            }
        }


        public delegate void DataReceived(string data);
        public event DataReceived OnDataReceived;

        public delegate void ConnetState(bool b);

        private void InitMingHuaIC()
        {
            //if (!File.Exists(ConfigPath.InWeightingRFID)) return;
            try
            {
                initMingHuaIC = new MingHuaICReader(SystemParam.ICCardSerialPortName);

                if (initMingHuaIC.OpenPort().Equals("成功"))
                {
                    MessageBox.Show("读卡器打开成功！");
                }
                else
                {
                    MessageBox.Show("读卡器打开失败！");
                    IcReaderState = false;//失败
                    return;
                }
                //initMingHuaIC.OnDataReceived += data =>
                //{
                //    Inrfid = data;
                //};

                //pdaComServer.DlgExceptionDataEvent -= new DlgExceptionData(this.DlgExceptionDataEventBack);
                //pdaComServer.DlgExceptionDataEvent += new DlgExceptionData(this.DlgExceptionDataEventBack);
                initMingHuaIC.OnDataReceived -= new MingHuaICReader.DataReceived(this.OnDataReceivedEventBack);
                initMingHuaIC.OnDataReceived += new MingHuaICReader.DataReceived(this.OnDataReceivedEventBack);

                initMingHuaIC.OnConnetState -= new MingHuaICReader.ConnetState(this.OnConnetStateEventBack);
                initMingHuaIC.OnConnetState += new MingHuaICReader.ConnetState(this.OnConnetStateEventBack);

            }
            catch (Exception e)
            {
                //throw;
            }
        }

        public void OnDataReceivedEventBack(string icCardNumber)
        {
            MessageBox.Show("卡号：" + icCardNumber);
            //开启定时器，30秒后自动关闭读取
            MessageBox.Show("结束读取卡号");
            initMingHuaIC?.StopRead();
        }
        public void OnConnetStateEventBack(bool icCardNumber)
        {
            MessageBox.Show("是否在线：" + icCardNumber);
        }

        private void InitCondition()
        {
            List<Entity.Condition> conditionsList = new List<Entity.Condition>();
            conditionsList.Add(new Entity.Condition() { cdCode = "", cdName = "" });//空的
            conditionsList.Add(new Entity.Condition() { cdCode = "ICardNum", cdName = "卡号" });
            conditionsList.Add(new Entity.Condition() { cdCode = "RegName", cdName = "司机" });
            conditionsList.Add(new Entity.Condition() { cdCode = "IdentityNum", cdName = "身份证号" });
            conditionsList.Add(new Entity.Condition() { cdCode = "Company", cdName = "发货单位" });
            conditionsList.Add(new Entity.Condition() { cdCode = "GoodsName", cdName = "货物" });
            conditionsList.Add(new Entity.Condition() { cdCode = "YNumber", cdName = "备案号" });
            conditionsList.Add(new Entity.Condition() { cdCode = "Plate", cdName = "车牌" });
            conditionsList.Add(new Entity.Condition() { cdCode = "Revicer", cdName = "收货单位" });
            conditionsList.Add(new Entity.Condition() { cdCode = "RegPhone", cdName = "司机手机" });
            conditionsList.Add(new Entity.Condition() { cdCode = "CardType", cdName = "卡类型" });

            cb_condition.ItemsSource = conditionsList;
            cb_condition.DisplayMemberPath = "cdName";
            cb_condition.SelectedValuePath = "cdCode";
        }

        private void InitCardType()
        {
            List<Entity.Condition> conditionsList = new List<Entity.Condition>();
            //conditionsList.Add(new Entity.Condition() { cdCode = "", cdName = "" });//空的
            conditionsList.Add(new Entity.Condition() { cdCode = "CardType1", cdName = "入厂货物制卡" });
            conditionsList.Add(new Entity.Condition() { cdCode = "CardType2", cdName = "出厂货物制卡" });
            conditionsList.Add(new Entity.Condition() { cdCode = "CardType3", cdName = "厂内流转货物制卡" });

            cb_cardType.ItemsSource = conditionsList;
            cb_cardType.DisplayMemberPath = "cdName";
            cb_cardType.SelectedValuePath = "cdCode";
        }


        private void OkClick(object sender, RoutedEventArgs e)
        {
            //弹出串口配置窗口
        }

        private void SearchClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("查找");
            SearchList();
        }

        private void BtnReport(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("开始读取卡号");
            initMingHuaIC.StartRead();
        }

        private void Pagination_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            var page = sender as HandyControl.Controls.Pagination;
            vm.PageIndex = page.PageIndex;
            SearchList();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SearchList();
        }
        void SearchList()
        {
            Task.Run(() => {
                try
                {
                    string msg = "";
                    //bool resutl = ServiceWebApi.CheckSulphuricAcid("蒙123456", "Y15220022878183", out msg);

                    int totalCount = 0;
                    BackInfo<ObservableCollection<T_RegisterInfo>> resutl = ServiceWebApi.QueryRegisterInfoByPage(1,20,out totalCount,"", out msg);

                    //if (ret.Code == 200 && ret.Data != null)
                    //{
                    //    vm.ModelList = ret.Data;
                    //    vm.PageCount = ret.Count / vm.PageSize + ((ret.Count % vm.PageSize) == 0 ? 0 : 1);
                    //}
                    //else
                    //    vm.ModelList = new ObservableCollection<CheckDevice>();

                    if (resutl != null)
                    {
                        if (resutl.code == 200)//查询成功
                        {
                            vm.ModelList = resutl.data;
                            vm.PageCount = resutl.totalCount;
                        }
                        else
                        {
                            // 
                            vm.ModelList = new ObservableCollection<Entity.T_RegisterInfo>();
                        }
                    }

                    //vm.Loading = Visibility.Visible;
                    //string resultStr = HttpHelper.Post("CheckDevice/GetPageList", JsonConvert.SerializeObject(vm));
                    //ReturnModel<ObservableCollection<CheckDevice>> ret = JsonConvert.DeserializeObject<ReturnModel<ObservableCollection<CheckDevice>>>(resultStr);

                    //if (ret.Code == 200 && ret.Data != null)
                    //{
                    //    vm.ModelList = ret.Data;
                    //    vm.PageCount = ret.Count / vm.PageSize + ((ret.Count % vm.PageSize) == 0 ? 0 : 1);
                    //}
                    //else
                    //    vm.ModelList = new ObservableCollection<CheckDevice>();

                    //加载数据


                    //数据--

                    //分页查询，几百天，就是几百条数据，
                }
                catch (Exception ex)
                {
                    //Growl.Warning("获取数据失败，请检查网络");
                    //LogHelper.Error(nameof(SearchList), ex);
                }
                finally
                {
                    vm.Loading = Visibility.Hidden;
                }
            });
        }

        private void AddClick(object sender, RoutedEventArgs e)
        {
            //01先查一下此卡是否归还，如果没有归还，则不能新增，需要提示先归还
            string msg = "";
            string CardNum = "5ED171DD";
            bool resutl = ServiceWebApi.QueryBackByCardNum(CardNum, out msg);
            if (resutl)
            {
                MessageBox.Show("此卡未归还，请先进行归还！");
                return;//提示此卡未归还，先选择归还，然后再进行发卡操作
            }

            //02完整性验证
            //1.如果是阴极铜则可以没有收发货单位，


            //几个地方进行修改 
            //配置信息，连上接口的时候弄，将

            //保存前调用一下另一个接口

            //将信息进行清空，并且  还有就是

            //开始读取卡号：

            //开始读卡
        }

        private void ICSettingClick(object sender, RoutedEventArgs e)
        {
            Window view = null;
            view = new Manual_ICSettingWindow();
            if (view != null)
            {
                view.Owner = this;
                view.ShowInTaskbar = false;
                view.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                view.ShowDialog();
            }
        }

        private void QueryClick(object sender, RoutedEventArgs e)
        {
            //根据条件进行查询发卡注册信息
            
            //卡号车号
        }

        private void Sender_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void UpdataClick(object sender, RoutedEventArgs e)
        {

        }

        private void DeleteClick(object sender, RoutedEventArgs e)
        {

        }
    }
}